"use strict"

module.exports = async function(){
    this.view = 'login';
    // this.branch = this.get('branch','string')
    // let _plaName=this.config.get('dbname');
     let setting = this.model.admin('setting');
     let ret=await setting.find({});
     if(ret&&ret.name){
        return ret.name;
     }else{ 
        return this.config.get('dbname');
     }
} 

// module.exports.sverify=function()
// {
//     let username = this.get('username','string');
//     let password = this.get('password','string');
//     if ( !username ) {
//         return this.error('用户名不能为空');
//     }
//     if ( !password ) {
//         return this.error('密码不能为空');
//     }
//     let guid = username;
//     let members = this.model.admin('members');
//     return members.exist(guid).then(ret=>{
//         if(ret) {
//             return module.exports.verify.call(this);
//         }
//         else
//         {
//             let info = {};
//             info['guid'] = username;
//             info['xcode'] = members.password(password);
//             info['name'] = username;
//             info['time'] = Date.now();
//             info['level'] = 100;
//             return members.insert(info).then(ret=>{
//                 return module.exports.verify.call(this);
//             })
//         }
//     })
// } 

module.exports.verify = function(){

    this.output = "json";
    let branch = this.get('branch','string')
    let username = this.get('username','string');
    let password = this.get('password','string');
    if ( !username ) {
        return this.error('用户名不能为空');
    }
    if ( !password ) {
        return this.error('密码不能为空');
    }
    let members = this.model.admin('members');
    let keys = ['_id','xcode','name','level','status'];
    return members.getFromName(username,keys).then(ret=>{
//        console.log(ret);
        if(!ret){
            return this.error('username not exist');
        }
        if(ret['status'] < 1){
            return this.error("账号已被禁用");
        }
        let verify_xcode = members.password(password);
        if( verify_xcode !== ret['xcode']){
            return this.error('password error');
        }
        return ret;
    }).then(ret=>{
        // if(!branch || ret['level'] >= 10){
        //     return ret;
        // }
        //拉出用户的auth矩阵
        let authorize = this.model.admin("authorize");
        return authorize.mget(ret._id).then(r=>{
            if(r){
               
                ret['auth']=r;
            }
            else{
                ret['auth']={};
            }
//            console.log(`uid:${ret._id} ret:${JSON.stringify(r)}`);
            return ret;
        });
    }).then(ret=>{
        let _id = ret['_id'],level = ret["level"]||0
        let query = {"name":ret['name'],"level":level,"auth":ret.auth};
        return this.session.create(_id,query);
    }).then(id=>{
        return {'k':this.session.opts.key,'v':id,'m':this.session.opts.method}
    })
};
